import dayjs from "dayjs";
import {
  ContestgetPage,
  Contestsave,
  Contestdelete
} from "@/api/teacher/contest";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";

export function useContest() {
  const ContestDto = reactive({
    ContestId: 0,
    ContestName: "",
    Remarks: ""
  });

  const updateContestDto = reactive({
    ContestId: 0,
    Remarks: "",
    ContestName: ""
  });
  const loadingTitle = ref("添加");
  const roleTypes = ref([]);
  const dataList = ref([]);
  const loading = ref(true);
  const addPanelVisible = ref(false);
  const updatePanelVisible = ref(false);
  const rules = {
    ContestName: [
      {
        required: true,
        message: "请输入竞赛名称！",
        trigger: ["blur", "change"]
      }
    ]
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "排序",
      type: "index",
      minWidth: 100
    },
    {
      label: "实训名称",
      prop: "contestName",
      minWidth: 120
    },
    {
      label: "创建时间",
      minWidth: 180,
      prop: "createTime",
      sortable: true,
      sortMethod: function (a, b) {
        return a - b;
      },
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "备注",
      prop: "remarks",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  function handleUpdate(row: any | undefined) {
    if (row) {
      loadingTitle.value = "修改竞赛";
      nextTick(() => {
        updateContestDto.ContestId = row.contestId;
        updateContestDto.ContestName = row.contestName;
        updateContestDto.Remarks = row.remarks;
      });
    } else {
      updateContestDto.ContestId = 0;
      loadingTitle.value = "添加竞赛";
    }
    updatePanelVisible.value = true;
  }

  function handleDelete(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const res = await Contestdelete({ contestId: row.contestId });
      if (res) {
        ElMessage.success(res.msg)
        onSearch();
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(() => { })


    // ElMessage({
    //   message: "删除成功",
    //   type: "success"
    // });

  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await ContestgetPage({
      pageindex: pagination.currentPage,
      pagesize: pagination.pageSize
    });

    dataList.value = data.list;
    pagination.total = data.totalCount;
    loading.value = false;
  }

  async function addContest(addDtoRef) {
    const respone = await Contestsave(ContestDto);
    if (respone.success) {
      onSearch();
      addPanelVisible.value = false;
      ElMessage({
        message: respone?.msg,
        type: "success"
      });
      addDtoRef.resetFields();
    }
  }

  function updateContest(addDtoRef: FormInstance | undefined) {
    (addDtoRef as any).validate(async valid => {
      if (!valid) return;
      const respone = await Contestsave(updateContestDto);
      console.log(respone);

      if (respone.status === 200) {
        onSearch();
        updatePanelVisible.value = false;
        ClosePanelVisible(addDtoRef);
        ElMessage({
          message: respone.msg,
          type: "success"
        });
      } else {
        ElMessage({
          message: respone.msg,
          type: "error"
        });
      }
    });
  }

  // 关闭
  function ClosePanelVisible(row: FormInstance | undefined) {
    if (!row) return;
    updatePanelVisible.value = false;
    row.resetFields();
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    rules,
    loading,
    columns,
    dataList,
    pagination,
    loadingTitle,
    addPanelVisible,
    ContestDto,
    updateContestDto,
    roleTypes,
    updatePanelVisible,
    onSearch,
    resetForm,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    ClosePanelVisible,
    handleCurrentChange,
    handleSelectionChange,
    addContest,
    updateContest
  };
}
